package com.freejava.testredis.demo.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class RedisUtil {

    /**
     * 注入操作Reids的工具类
     */
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 查询一个key对应的value
     * @param key
     * @return
     */
    public String get(final String key) {
        return redisTemplate.opsForValue().get(key);
    }

    /**
     * 设置指定key对应的value
     * @param key
     * @param value
     * @return
     */
    public boolean set(final String key, String value) {
        boolean result = false;
        try {
            redisTemplate.opsForValue().set(key, value);
            result = true;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    // 返回老的值，并且把值更新
    public String getAndSet(final String key, String value) {
        String result = "";
        try {
            String oldValue = redisTemplate.opsForValue().getAndSet(key, value);
            result = oldValue;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }

    /**
     * 删除指定的key
     * @param key
     * @return
     */
    public boolean delete(final String key) {
        boolean result = false;
        try {
            redisTemplate.delete(key);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }

    /**
     * 判断某个key是否存在
     * @param key
     * @return
     */
    public boolean hasKey(String key) {
        boolean result = false;
        try {
            return redisTemplate.hasKey(key);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 给指定的key设置过期时间
     * @param key
     * @param time
     * @return
     */
    public boolean expire(String key, long time) {
        boolean result = false;
        try {
            return redisTemplate.expire(key, time, TimeUnit.SECONDS);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

}
